import { Injectable } from '@nestjs/common';
import ExamDistrictQueryParam from '../param/ExamDistrictQueryParam';
import { PrismaService } from 'src/common/prisma/PrismaService';
import ExamDistrictVo from '../vo/ExamDistrictVo';
import { plainToInstance } from 'class-transformer';
import ExamDistrictDto from '../dto/ExamDistrictDto';
import ServiceException from 'src/common/ServiceException';

/*
 * @Author: jingfuu@163.com
 * @Date: 2024-12-16 09:50:27
 * @LastEditTime: 2024-12-16 11:17:54
 * @Description: 考点
 */
@Injectable()
class ExamDistrictService {
  constructor(private prisma: PrismaService) {}

  async findExamDistrictList(param: ExamDistrictQueryParam) {
    const skip = param.pageNum != 0 ? (param.pageNum - 1) * param.pageSize : 0;
    const whereClause: any = this.generatePageQueryCondition(param);
    const [total, list] = await this.prisma.$transaction([
      this.prisma.examDistrict.count({ where: whereClause }),
      this.prisma.examDistrict.findMany({
        skip,
        take: param.pageSize,
        orderBy: {
          createTime: 'desc',
        },
        where: whereClause,
      }),
    ]);
    const rows: ExamDistrictVo[] = plainToInstance(ExamDistrictVo, list);
    return {
      total,
      rows,
    };
  }
  generatePageQueryCondition(param: ExamDistrictQueryParam): any {
    const whereClause: any = {};

    if (param.name) {
      whereClause.name = {
        contains: param.name,
      };
    }
    return whereClause;
  }

  async detail(id: number) {
    const examDistrict = await this.prisma.examDistrict.findUnique({
      where: {
        id,
      },
    });
    return plainToInstance(ExamDistrictVo, examDistrict);
  }

  async modifyExamDistrict(examDistrict: ExamDistrictDto) {
    await this.checkExamDistrictName(examDistrict.name, examDistrict.id);
    await this.prisma.examDistrict.update({
      where: {
        id: examDistrict.id,
      },
      data: {
        name: examDistrict.name,
        address: examDistrict.address,
      },
    });
  }
  async createExamDistrict(examDistrict: ExamDistrictDto) {
    await this.checkExamDistrictName(examDistrict.name, examDistrict.id);
    await this.prisma.examDistrict.create({
      data: {
        name: examDistrict.name,
        address: examDistrict.address,
      },
    });
  }
  async checkExamDistrictName(name: string, id: number) {
    const examDistrict = await this.prisma.examDistrict.findFirst({
      where: {
        name: name,
      },
    });
    if (!id) {
      if (examDistrict) {
        throw new ServiceException('考试区域：' + name + '已存在');
      }
    } else {
      if (examDistrict && examDistrict.id != id) {
        throw new ServiceException('考试区域：' + name + '已存在');
      }
    }
  }

  async deleteExamDistrict(id: number) {
    await this.prisma.examDistrict.delete({ where: { id } });
  }
}
export default ExamDistrictService;
